# -*- coding: utf-8 -*-
"""
@Time ： 2023/4/4 21:31
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：京东验证码破解
@Install：pip install pyautogui
"""
import base64
import time

import pyautogui
from selenium.webdriver import ActionChains

from class08.homework import MyWeb
from class10.slide import FindPic

web = MyWeb()
web.open_browser()
driver = web.driver

driver.get('https://passport.jd.com/new/login.aspx')

driver.find_element('xpath', '//a[text()="账户登录"]').click()
driver.find_element('xpath', '//*[@id="loginname"]').send_keys('wuqindsfagfqndfg')
driver.find_element('xpath', '//*[@id="nloginpwd"]').send_keys('123dskafj')
driver.find_element('xpath', '//*[@id="loginsubmit"]').click()

while True:
    # 图片元素
    ele_big = driver.find_element('xpath', '//div[@class="JDJRV-bigimg"]/img')
    ele_small = driver.find_element('xpath', '//div[@class="JDJRV-smallimg"]/img')

    # 滑块没显示就停止（我们认为破解成功了）
    if ele_big.size.get('width') < 10:
        break

    # 获取图片的src属性
    big_src = ele_big.get_attribute('src')
    big_src = big_src[22:]

    small_src = ele_small.get_attribute('src')
    small_src = small_src[22:]

    # 字符串decode为二进制
    imgdata = base64.b64decode(big_src)
    # 打开一张图片：用写入二进制的模式
    file = open('big.jpg', mode='wb')
    # 写入图片的二进制
    file.write(imgdata)
    # 关闭保存
    file.close()

    # 字符串decode为二进制
    imgdata = base64.b64decode(small_src)
    # with上下文，提供了文件操作的自动保存关闭功能
    with open('small.jpg', mode='wb') as f:
        f.write(imgdata)

    x = FindPic("./big.jpg", "./small.jpg")
    print(x)

    # 处理网页缩放
    x = int(x * 278 / 360 * 1.25)

    # action = ActionChains(driver)
    # # 先按住小滑块，移动x距离，松开鼠标（操作生效）
    # action.click_and_hold(ele_small).move_by_offset(x,0).release().perform()
    # time.sleep(3)

    # 获取滑块位置（起始位置，相对屏幕最上方
    xx = int(ele_small.location.get('x') * 1.25) + 20
    yy = int(ele_small.location.get('y') * 1.25) + 20 + 90

    # pyautogui
    # 移动到滑块
    pyautogui.moveTo(xx, yy)
    # 按住鼠标
    pyautogui.mouseDown(xx, yy)
    # 拖动鼠标：先拖过头
    pyautogui.moveTo(xx + x + 20, yy + 10, 0.3)
    # 拖回去
    pyautogui.moveTo(xx + x - 10, yy + 3, 0.2)
    # 再拖动准确
    pyautogui.moveTo(xx + x, yy - 3, 0.2)
    # 松开鼠标
    pyautogui.mouseUp()

    time.sleep(3)
